<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>客户端A</title>
</head>

<body>
  <div>
    <video id="video" muted autoplay controls width="400px"></video>
  </div>

  <script src="/client/socket.io/socket.io.js"></script>
  <script>
    let videoDom = document.getElementById('video')
    let localSteam

    // socket.io 连接
    const socket = io.connect('http://localhost:9898')
    socket.emit('joinRoom', '123')

    socket.on('create', (room) => {
      console.log('创建或加入房间' + room)
    })
    // 接电话
    socket.on('call', (msg) => {
      console.log(msg)
      if (msg === 'refresh') {
        createRTC()
      }
    })

    // 获取媒体设备
    navigator.getUserMedia = navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia;

    if (navigator.getUserMedia) {
      // 支持
      console.log(navigator.getUserMedia)
      navigator.getUserMedia({ video: true, audio: true }, onSuccess, onError)
    } else {
      // 不支持
      console.log('该浏览器不支持获取音视频')
    }
    // 打开视频成功
    function onSuccess(stream) {
      localSteam = stream
      videoDom.srcObject = stream
      videoDom.play()
      createRTC()
    }
    // 打开视频失败
    function onError(err) {
      console.log('打开视频失败')
      console.log(err)
    }

    // webRtc通信
    let config = {
      iceServers: [
        {
          urls: 'stun:stun.l.google.com:19302'
        }
      ]
    }
    let pc
    const offerOptions = {
      offerToReceiveVideo: 1,
      offerToReceiveAudio: 1
    };
    function createRTC() {
      // 创建RTC
      pc = new RTCPeerConnection(config)
      // 视频流添加
      pc.addStream(localSteam)
      // 创建offer 的 SDP 对象
      pc.createOffer(offerOptions).then((offer) => {
        // 创建成功后通过signal服务器发送给clientB
        pc.setLocalDescription(offer)
        socket.emit('signal', offer, '123')
      }).catch((err) => {
        console.log(err)
      })
      // 接收到candidate信息后，通过onIceCandidate 接口发送给ClientB
      pc.addEventListener('icecandidate', event => {
        let icecandidate = event.candidate
        if (icecandidate) {
          socket.emit('ice', icecandidate, '123')
        }
      })
    }

    socket.on('signal', (offer) => {
      // 接受保存clientA的应答SDP对象
      if (pc !== 'undefined') {
        pc.setRemoteDescription(new RTCSessionDescription(offer))
      }
    })
    
    socket.on('ice', (message) => {
      if (pc !== 'undefined') {
        try {
          pc.addIceCandidate(new RTCIceCandidate(message));
        } catch (err) {
          console.log(err)
        }
      }
    })

  </script>
</body>

</html>